package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.JwShoproGoods;
import com.dianban.entity.ShopUser;
import com.dianban.entity.User;
import com.dianban.service.FacePayConfigService;
import com.dianban.service.JwShoproGoodsService;
import com.dianban.service.ShopUserService;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Api(value = "ApiShoproGoodsController", description = "商品控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/goods/")
public class ApiShoproGoodsController extends BaseController {

    @Value("${rongyaotuadmin.domain}")
    private String rongyaotuadminDomain;

    @Autowired
    private JwShoproGoodsService jwShoproGoodsService;
    @Autowired
    private ShopUserService shopUserService;
    @Autowired
    private FacePayConfigService facePayConfigService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "获取所有商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "storeId", value = "门店id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "type", value = "类型，不传查的是荣耀兔，传box表示有机饭盒", required = true, paramType = "query", dataType = "string"),

    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(String storeId, @RequestParam(value = "type", required = false, defaultValue = "") String type, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<JwShoproGoods> goodsList = new ArrayList<>();
        try {
            if (StringUtils.isEmpty(type)) {
                // 增加配置，针对特定的门店是否出现这些商品，可以定制展示
                List<FacePayConfig> facePayConfigList = facePayConfigService.find(40, 1, Long.valueOf(storeId));
                String noShowIds = "";
                List<String> noShowIdList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(facePayConfigList)) {
                    noShowIds = facePayConfigList.get(0).getValue();
                    if (StringUtils.isNotBlank(noShowIds)) {
                        String[] split = noShowIds.split(",");
                        for (String noShowId : split) {
                            noShowIdList.add(noShowId);
                        }
                    }
                }

                List<JwShoproGoods> goods = new ArrayList<>();
                List<JwShoproGoods> goods1 = jwShoproGoodsService.findList("60");
                // 特定门店
                //List<JwShoproGoods> goods2 = jwShoproGoodsService.findList("64");
                // 敬心爱老
                List<JwShoproGoods> goods3 = jwShoproGoodsService.findList("65");
                goods.addAll(goods1);
                //goods.addAll(goods2);
                goods.addAll(goods3);
                if (!CollectionUtils.isEmpty(goods) && StringUtils.isNotBlank(noShowIds) && !CollectionUtils.isEmpty(noShowIdList)) {
                    for (JwShoproGoods jwShoproGoods : goods) {
                        //if (!noShowIds.contains(String.valueOf(jwShoproGoods.getId()))) {
                        if (!noShowIdList.contains(String.valueOf(jwShoproGoods.getId()))) {
                            goodsList.add(jwShoproGoods);
                        }
                    }
                } else {
                    goodsList.addAll(goods);
                }
                // 判断下是否门店老板
                if (StringUtils.isNotBlank(storeId)) {
                    // 判断下是不是当前门店老板,是的话特殊处理
                    ShopUser shopUser = shopUserService.findByStoreId(Long.valueOf(storeId));
                    if (shopUser != null && shopUser.getId().equals(user.getId())) {
                        goodsList.addAll(jwShoproGoodsService.findList("61"));
                    }
                }
            } else if("box".equalsIgnoreCase(type)){
                // 查询显示的是有机饭盒
                List<JwShoproGoods> goods1 = jwShoproGoodsService.findList("67");
                goodsList.addAll(goods1);
            }
            // TODO:判断下如果有购买过9.9就不出现这个商品
            if (!CollectionUtils.isEmpty(goodsList)) {
                for (JwShoproGoods jwShoproGoods : goodsList) {
                    if (StringUtils.isNotBlank(jwShoproGoods.getImage())) {
                        jwShoproGoods.setImage(jwShoproGoods.getImage().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
                    }
                    if (StringUtils.isNotBlank(jwShoproGoods.getImages())) {
                        jwShoproGoods.setImages(jwShoproGoods.getImages().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
                    }
                    if (StringUtils.isNotBlank(jwShoproGoods.getContent())) {
                        jwShoproGoods.setContent(jwShoproGoods.getContent().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(goodsList, "获取成功");
    }

    @ApiOperation(notes = "info", httpMethod = "GET", value = "获取商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "id", value = "商品id", required = true, paramType = "query", dataType = "string"),

    })
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public ResultVo info(String id, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        JwShoproGoods jwShoproGoods = null;
        try {
            jwShoproGoods = jwShoproGoodsService.findById(Long.valueOf(id));
            if (jwShoproGoods == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该商品");
            }
            if (StringUtils.isNotBlank(jwShoproGoods.getImage())) {
                jwShoproGoods.setImage(jwShoproGoods.getImage().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
            }
            if (StringUtils.isNotBlank(jwShoproGoods.getImages())) {
                jwShoproGoods.setImages(jwShoproGoods.getImages().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
            }
            if (StringUtils.isNotBlank(jwShoproGoods.getContent())) {
                jwShoproGoods.setContent(jwShoproGoods.getContent().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(jwShoproGoods, "获取成功");
    }

}
